//
//  MapSelPlaceViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/8.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "MapSelPlaceViewController.h"

#import "CityModel.h"
@interface MapSelPlaceViewController ()<BMKLocationServiceDelegate,BMKMapViewDelegate,BMKGeoCodeSearchDelegate,UITableViewDataSource,UITableViewDelegate>{
    BMKMapView *_mapView;
    BMKLocationService *locationService;
    
    BMKPinAnnotationView *newAnnotation;
    
    BMKGeoCodeSearch *_geoCodeSearch;
    
    BMKReverseGeoCodeOption *_reverseGeoCodeOption;
    
    CGFloat lat;
    CGFloat lng;
}

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *array;

@property (nonatomic,copy)UIButton *btn;

@property (nonatomic,copy)NSString *city;
@property (nonatomic,copy)NSString *area;

@end

@implementation MapSelPlaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    _array = [NSMutableArray array];
    [self showNav:@"选择位置"];
    [self loadUI];
    
}

- (void)loadUI{
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, (ScreenHeight-64)/2)];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
//    [_mapView setMapType:BMKMapTypeStandard];
    [self.view addSubview:_mapView];
    
    _btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn setImage:[UIImage imageNamed:@"serach_Map"] forState:UIControlStateNormal];
    [_mapView addSubview:_btn];
    [_btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_mapView.centerX);
        make.centerY.equalTo(_mapView.centerY);
        make.height.width.equalTo(35);
    }];
    
    locationService = [[BMKLocationService alloc] init];
    locationService.delegate = self;
    //开启定位
    [locationService startUserLocationService];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, (ScreenHeight-64)/2+64, ScreenWidth, (ScreenHeight-64)/2) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
}
#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    
    CityModel *model = _array[indexPath.row];
    cell.detailTextLabel.text = model.address;
    cell.textLabel.text = model.name;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CityModel *model = _array[indexPath.row];
    [self.delegate sendText:model.address Province:_city City:_city Area:_area];
    
    [self.delegate sendAddress:model.address Det:model.name];
    
    [self.delegate sendLat:[NSString stringWithFormat:@"%f",lat] sendLng:[NSString stringWithFormat:@"%f",lng]];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    _mapView.showsUserLocation = YES;
    //设置地图中心为用户经纬度
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = userLocation.location.coordinate;
    _mapView.zoomLevel = 18.0;
    
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    
    //获取城市
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks > 0) {
            CLPlacemark *mark = [placemarks objectAtIndex:0];
            if (mark) {
                
                //NSLog(@"c%@",mark.subLocality);//区域
                //NSLog(@"b%@",mark.locality);
                _city = mark.locality;//城市
                _area = mark.subLocality;
                if (!_city) {
                    _city = mark.administrativeArea;
                }
                
            }
        }
    }];
    
//    BMKCoordinateRegion region ;//表示范围的结构体
//    region.center = _mapView.centerCoordinate;//中心点
//    
//    [_mapView setRegion:region animated:YES];
}

#pragma mark BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    //屏幕坐标转地图经纬度
    CLLocationCoordinate2D MapCoordinate=[_mapView convertPoint:_btn.center toCoordinateFromView:_mapView];
    
    if (_geoCodeSearch==nil) {
        //初始化地理编码类
        _geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
        _geoCodeSearch.delegate = self;
        
    }
    if (_reverseGeoCodeOption==nil) {
        
        //初始化反地理编码类
        _reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    }
    
    //需要逆地理编码的坐标位置
    _reverseGeoCodeOption.reverseGeoPoint =MapCoordinate;
    [_geoCodeSearch reverseGeoCode:_reverseGeoCodeOption];
}

#pragma mark BMKGeoCodeSearchDelegate
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    //获取周边用户信息
    if (error==BMK_SEARCH_NO_ERROR) {
        //
        [_array removeAllObjects];
        for(BMKPoiInfo *poiInfo in result.poiList)
        {
            NSString *name = poiInfo.name;
            NSString *address = poiInfo.address;
            
            CityModel *model = [[CityModel alloc] init];
            model.name = name;
            model.address = address;
            [_array addObject:model];
            [_tableView reloadData];
        }
        
    }else{
        NSLog(@"BMKSearchErrorCode: %u",error);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
